package com.tepth.remote.control.delegate.file;

import com.alibaba.fastjson.JSONObject;
import com.tepth.remote.control.base.bean.FileBean;
import com.tepth.remote.core.utils.file.FileUtil;
import com.tepth.remote.ui.recycler.BaseDataConverter;
import com.tepth.remote.ui.recycler.ItemType;
import com.tepth.remote.ui.recycler.MultipleFields;
import com.tepth.remote.ui.recycler.MultipleItemEntity;

import java.io.File;
import java.util.ArrayList;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/22
 */
public class FileDataConvert extends BaseDataConverter {
    @Override
    public ArrayList<MultipleItemEntity> convert() {
        final ArrayList<JSONObject> soapArray = getSoapArray();
        final int size = soapArray.size();
        for (int i = 0; i < size; i++) {
            final JSONObject object = soapArray.get(i);
            FileBean bean = new FileBean()
                    .setId(object.getInteger("FI_Id"))
                    .setName(object.getString("FI_Name"))
                    .setUrl(object.getString("FI_Url"))
                    .setSize(object.getString("FI_Size"))
                    .setState(object.getInteger("FI_State"))
                    .setType(object.getInteger("FI_Type"))
                    .setUserId(object.getString("FI_UserId"))
                    .setCreateDate(object.getString("FI_CreateDate"));
            final File file = FileUtil.getFile(bean.getName() + bean.getUrl().substring(
                    bean.getUrl().lastIndexOf("."),
                    bean.getUrl().length()));
            int fileStatus;
            if (file.exists()) {
                fileStatus = ItemType.FILE_COMPLETE;
            } else {
                fileStatus = ItemType.FILE_NOT_FOUND;
            }
            final MultipleItemEntity entity = MultipleItemEntity.builder()
                    .setItemType(ItemType.FILE_LIST)
                    .setField(MultipleFields.TITLE, bean.getName())
                    .setField(MultipleFields.TEXT, bean.getCreateDate())
                    .setField(MultipleFields.SPAN_SIZE, bean.getSize())
                    .setField(MultipleFields.ID, bean.getId())
                    .setField(MultipleFields.TAG, fileStatus)
                    .setField(MultipleFields.FILE_BEAN, bean)
                    .builder();
            ENTITIES.add(entity);
        }
        return ENTITIES;
    }

    private ArrayList<JSONObject> getSoapArray() {
        final ArrayList<JSONObject> soapArray = new ArrayList<>();
        final ArrayList<Object> array = getArrays();
        final int size = array.size();
        for (int i = 0; i < size; i++) {
            soapArray.add((JSONObject) array.get(i));
        }
        return soapArray;
    }
}
